package cn.lili;

import java.io.IOException;
import java.util.Date;
import java.util.concurrent.ConcurrentHashMap;
import javax.websocket.*;
import javax.websocket.server.PathParam;
import javax.websocket.server.ServerEndpoint;

import cn.lili.po.MessageType;
import org.springframework.stereotype.Component;
import com.alibaba.fastjson.JSON;
import cn.lili.po.Message;

/**
 * @author liushuai
 */
@Component
@ServerEndpoint("/lili/webSocket/{username}")
public class WebSocketServer {
    /**
     * 在线人数
     */
    private static ConcurrentHashMap<String, Session> sessionPools = new ConcurrentHashMap<>();


    /**
     * 建立连接
     *
     * @param session
     */
    @OnOpen
    public void onOpen(@PathParam("username") String username, Session session, EndpointConfig endpointConfig) {

        sessionPools.put(username, session);
        //上下线通知
        currentUser();
    }

    /**
     * 关闭连接
     */
    @OnClose
    public void onClose(@PathParam("username") String username) {

        sessionPools.remove(username);
        //上下线通知
        currentUser();
    }

    /**
     * 发送消息
     *
     * @param msg
     * @throws IOException
     */
    @OnMessage
    public void onMessage(String msg) {
        Message message = JSON.parseObject(msg, Message.class);
        message.setDate(new Date());
        message.setMessageType(MessageType.MESSAGE);
        Session session = sessionPools.get(message.getTo());
        try {
            if (session != null) {
                session.getBasicRemote().sendText(JSON.toJSONString(message, true));
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * socket exception
     *
     * @param session
     * @param throwable
     */
    @OnError
    public void onError(Session session, Throwable throwable) {
        throwable.printStackTrace();
    }

    /**
     * 当前用户
     */
    public void currentUser() {

        for (String key : sessionPools.keySet()) {
            Message message = new Message();
            Session session = sessionPools.get(key);
            message.setMessageType(MessageType.ONLINE);
            message.setUsers(sessionPools.keySet());
            try {
                session.getBasicRemote().sendText(JSON.toJSONString(message, true));
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }

    /**
     * 获取websocket 键值对
     *
     * @return
     */
    public ConcurrentHashMap<String, Session> getSessionPools() {
        return sessionPools;
    }
}
